package 剑指Offer.medium;

public class 矩阵中的路径 {
    class Solution {

        public boolean exist(char[][] board, String word) {
            char[] words = word.toCharArray();
            int length = words.length;
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (dfs(board, words, i, j, 0)) return true;
                }
            }
            return false;
        }

        /**
         * @param board 字典
         * @param word  单词
         * @param i     当前坐标
         * @param j     当前坐标
         * @param k     匹配单词的深度
         * @return
         */
        private boolean dfs(char[][] board, char[] word, int i, int j, int k) {
            if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word[k]) {
                return false;
            }
            if (k == word.length - 1) return true;
            //如果字符匹配 board[i][j] == word[k]
            board[i][j] = '\0';
            boolean result = dfs(board, word, i - 1, j, k + 1) ||
                            dfs(board, word, i + 1, j, k + 1) ||
                            dfs(board, word, i, j - 1, k + 1) ||
                            dfs(board, word, i, j + 1, k + 1);
            board[i][j] = word[k];
            return result;
        }
    }
}
